package com.runa.persistence.check;

import com.runa.monitor.comm.dto.newComm.AsynResult;
import com.runa.monitor.comm.enums.NetEquTypeEnum;
import com.runa.persistence.DateUtil;
import lombok.Data;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 2024/7/4 9:28
 * zhangYB
 */
@Data
public class DownTaskNetEquip {

    private String id;

    private String serial;

    private Integer equCount = 0;

    private String type;

    private boolean finished =  false;
    private String finishTime;

    private AtomicInteger downCount = new AtomicInteger(0);

    private AtomicInteger pendingUpCount = new AtomicInteger(0);

    private AtomicInteger successUpCount = new AtomicInteger(0);

    private AtomicInteger failedUpCount = new AtomicInteger(0);

    private AtomicInteger queuedCount =  new AtomicInteger(0);


    private void increase(AtomicInteger count) {
        increase(count, 1);
    }

    private void increase(AtomicInteger count, int size) {
        if (null == count) {
            return;
        }
        int oldCount = count.get();
        while (!count.compareAndSet(oldCount, oldCount+size)) {
            oldCount = count.get();
        }
    }

    public void queueCount(int size) {
        increase(queuedCount, size);
    }


    public void failedUpCount() {
        increase(failedUpCount);
        finishCheck();
    }


    public void successUpCount() {
        increase(successUpCount);
        finishCheck();
    }


    private AtomicInteger successCount = new AtomicInteger(0);

    private AtomicInteger failedCount = new AtomicInteger(0);

    public void result(boolean b) {
        if (b) {
            increase(successCount);
        } else {
            increase(failedCount);
        }
    }


    public void pendingUpCount() {
        increase(pendingUpCount);
    }


    public void downCount(int size) {
        increase(downCount, size);
    }

    private void finishCheck() {
        if (equCount == (successUpCount.get() + failedUpCount.get())) {
            finished = true;
            finishTime = DateUtil.milliTimeNow();
        }
    }

    public String check() {
        return String.valueOf(finished);
    }

    @Override
    public String toString() {
        return "设备数量=" + equCount +
                ", 类型='" + type +
                ", 下发数量=" + downCount +
                ", 成功数量=" + successCount +
                ", 失败数量=" + failedCount +
                ", 成功上报数量=" + successUpCount +
                ", 失败上报数量=" + failedUpCount +
                ", 正在上报数量=" + pendingUpCount +
                ", 结束时间=" + finishTime;
    }

    public void addEquCount(int size) {
        equCount += size;
    }

    public void setType(NetEquTypeEnum type) {
        if (null != this.type) {
            this.type = this.type + type.name();
        } else {
            this.type = type.name();
        }

    }
}
